<template>
  <div>
    <img class="poster-background" :src="list.length && list[currentIndex].posterSrc" />
    <x-header  style="background: rgba(255,255,255,0);font-size:17px" :left-options="{backText: ''}"><p style="color: #fff;">展示海报</p></x-header>
    <div class="poster-card" v-if="viewReady">
      <!--<div class="card-switch-title">展示个性名片</div>x-->
      <x-switch title="展示个性名片" class="switch" v-model="detail.status" @on-change="switchStatus"/>
      <div class="button" style="width:4.5rem;margin-left: auto;background: #000">
        <x-button  class="card-edit" plain mini type="primary" @click.native="edit" >编辑名片</x-button>
      </div>
    </div>
    <div style="width: 70%;padding: 0 15%" >
      <swiper style="width:100%" height="27.85rem" :show-dots="false" :auto="false" v-model="currentIndex" @on-index-change="slide" :custom="true" overflow="visible">
        <swiper-item v-for="(item,index) in list" :key="index">
          <div :ref="`poster${index}`" style="height: 100%;width: 100%">
            <img class="swiper-poster" :src="detail.status? item.imgUrl||item.posterSrc:item.posterSrc" />
            <div v-if="!item.imgUrl && detail.status" class="swiper-poster-card"  >
              <p class="swiper-poster-card-name">{{detail.name}}</p>
              <p class="swiper-poster-card-phone">{{detail.mobile}}</p>
            </div>
          </div>
        </swiper-item>
      </swiper>
    </div>
    <!--<x-button id="poster-save" plain @click.native="saveToAlbum">保存到本地</x-button>-->
    <div v-if="showCard" class="poster-edit">
      <div class="model">
        <img class="close" src="../../../static/img/close.png" @click="close" />
        <div class="title">名片编辑</div>
        <div class="input-name" >
          <x-input class="pad-l-r-0" placeholder="请输入姓名" type="text" :max="4" v-model="detail.name" />
        </div>
        <div class="input-mobile">
          <x-input class="pad-l-r-0" placeholder="请输入手机号" mask="99999999999" :max="11" v-model="detail.mobile" />
        </div>
        <div >
          <x-button class="edit-save-button pad-l-r-0" type="primary" @click.native="editPosterHandle">保存</x-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import { throttle } from 'vux'
import { getUserPosterList, editPoster, getPosterList } from '@/api/user'
import html2canvas from 'html2canvas'

export default {
  name: 'index',
  components: {
  },
  data () {
    return {
      viewReady: false,
      list:[],
      currentIndex:0,
      showCard: 0,
      detail: { id: '',name:'',mobile:'',status: 0 },
      posterId: 1,
      imgUrl: '',
    }
  },
  methods: {
    switchStatus (status) {
      // if (status && !this.list[0].imgUrl) {
      //   this.eleToImg()
      // }
    },
    slide() {
      this.currentIndex = arguments[0]
      if (!this.list[arguments[0]].imgUrl) {
        this.$nextTick(()=>{
          this.eleToImg()
        })
      }
    },
    edit () {
      this.showCard = 1
    },
    close () {
      this.showCard = 0
    },
    editPosterHandle () {
      editPoster({id:this.detail.id, cid: this.globalData.cid, posterId: this.posterId,name:this.detail.name, mobile: this.detail.mobile, status: 1}).then(()=>{
        this.showCard = 0
        this.detail.status = true
        this.$vux.toast.show({
          text: '修改成功',
          type: 'success'
        })
        this.list = this.list.map(item => {
          item.imgUrl = ''
          return item
        })
        this.eleToImg()
      })
    },
    //下载
    downloadFile(fileName, content) {
      // let alink = document.createElement("a");
      // alink.href = this.imageUrl;
      // alink.download = "loan_qrcode"; //图片名
      // alink.click();
      let aLink = document.createElement('a');
      let blob = this.base64ToBlob(content); //new Blob([content]);
      let file = this.blobToFile(blob, fileName);
      let evt = document.createEvent("HTMLEvents");
      evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
      aLink.download = fileName;
      aLink.href = URL.createObjectURL(file);
      alert(aLink.href)
      // if(window.Blob) alert('不支持');
      // aLink.dispatchEvent(evt);
      // aLink.click()
      aLink.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: false, view: window}));//兼容火狐

    },
    //base64转blob
    base64ToBlob(code) {
      let parts = code.split(';base64,');
      let contentType = parts[0].split(':')[1];
      let raw = window.atob(parts[1]);
      let rawLength = raw.length;
      let uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], {type: contentType});
    },
    // blob 转换为file
    blobToFile: function(theBlob, fileName){
      theBlob.lastModifiedDate = new Date();
      theBlob.name = fileName;
      return theBlob;
    },
    saveToAlbum () {
      let that = this
      let ua = window.navigator.userAgent.toLowerCase()
      if(ua.indexOf('micromessenger') !== -1){
        this.$vux.toast.show({
          text: '请点击右上角浏览器打开',
          type: 'text'
        })
      }else{
        if (this.list.length) {
          html2canvas(this.$refs['poster' + this.currentIndex][0],{
            useCORS: true,
            logging:false,
            width: this.$refs[`poster${this.currentIndex}`][0].clientWidth,
            height: this.$refs[`poster${this.currentIndex}`][0].clientHeight
          }).then(function(canvas) {
            //that.imgUrl = URL.createObjectURL(that.base64ToBlob(canvas.toDataURL()))
            that.imgUrl = canvas.toDataURL("image/png")
            that.downloadFile('loan_poster.png', that.imgUrl);
          });
        }
      }
    },
    eleToImg() {
      let that = this
      html2canvas(this.$refs[`poster${this.currentIndex}`][0],{
        useCORS: true,
        logging:false,
        width: this.$refs[`poster${this.currentIndex}`][0].clientWidth,
        height: this.$refs[`poster${this.currentIndex}`][0].clientHeight
      }).then(function(canvas){
        that.$set(that.list[that.currentIndex],'imgUrl', canvas.toDataURL("image/png"))
      })
    }
  },
  mounted () {
    getPosterList().then( data => {
      this.list = data
      getUserPosterList(this.globalData.cid).then(data => {
        data.status = !!data.status
        this.detail = data
        this.list.forEach( (item, index) => {
          if (item.id === data.posterId) {
            this.currentIndex = index
          }
          this.$nextTick(()=>{
            this.viewReady = true
            this.eleToImg()
          })
        })
      },() => {
        data.status = false
        this.viewReady = true
      })
    })
    this.$vux.toast.text('长按海报保存到相册')
  }
}
</script>

<style scoped>
.swiper-poster {
  width: 100%;
  height: 100%;
  display:block
}
.swiper-poster-card {
  position: absolute;
  left: 0;top: 23.2rem;
  background: rgba(0,0,0,0.40);
  width: 100%;
  height: 45px;
  color: rgba(255,255,255,0.80);
  line-height: 45px;
}
.swiper-poster-card-name {
  padding-left: 15px;
  display: inline;
}
.swiper-poster-card-phone {
  padding-left: 10px;
  display: inline;
}
</style>
